<template>
  <div class="login-container">
    <div class="login-header">
      <van-icon name="arrow-left" size="24" color="#000" @click="goBack" />
    </div>

    <div class="login-content">
      <div class="logo-wrap">
        <div class="slogan">记录美好生活</div>
      </div>
      <div class="login-form">
        <van-form @submit="onSubmit" validate-trigger="onSubmit">
          <van-cell-group inset>
            <van-field
              v-model="formData.phone"
              type="tel"
              maxlength="11"
              placeholder="请输入手机号"
              :rules="mobileRules"
            >
              <template #left-icon>
                <van-icon name="phone-o" size="16" />
              </template>
            </van-field>

            <!-- 验证码登录表单 -->
            <template v-if="loginType === 'code'">
              <van-field
                v-model="formData.code"
                center
                clearable
                placeholder="请输入验证码"
                :rules="codeRules"
              >
                <template #left-icon>
                  <van-icon name="shield-o" size="16" />
                </template>
                <template #button>
                  <van-button
                    size="small"
                    type="primary"
                    :disabled="isCountingDown"
                    @click="sendCode"
                  >
                    {{ countDownText }}
                  </van-button>
                </template>
              </van-field>
            </template>

            <!-- 密码登录表单 -->
            <template v-else>
              <van-field
                v-model="formData.password"
                :type="showPassword ? 'text' : 'password'"
                placeholder="请输入密码"
                :rules="passwordRules"
              >
                <template #left-icon>
                  <van-icon name="lock" size="16" />
                </template>
                <template #right-icon>
                  <van-icon
                    :name="showPassword ? 'eye-o' : 'closed-eye'"
                    size="16"
                    @click="showPassword = !showPassword"
                  />
                </template>
              </van-field>
            </template>
          </van-cell-group>
          <div class="login-type-wrap">
            <!-- 登录方式切换 -->
            <div class="login-type">
              <span v-if="loginType === 'password'" @click="loginType = 'code'">验证码登录</span>
              <span v-if="loginType === 'code'" @click="loginType = 'password'">密码登录</span>
            </div>

            <!-- 密码登录时显示忘记密码 -->
            <div v-if="loginType === 'password'" class="forget-password">
              <span @click="forgetPassword">忘记密码？</span>
            </div>
          </div>

          <div class="submit-btn">
            <van-button round block type="primary" native-type="submit" :disabled="submitDisabled">
              登录
            </van-button>
          </div>
        </van-form>

        <div class="other-login">
          <div class="divider">
            <span class="line"></span>
            <span class="text">其他登录方式</span>
            <span class="line"></span>
          </div>
          <div class="login-methods">
            <div class="method-item">
              <van-icon name="wechat" size="24" color="#000" />
              <span>微信</span>
            </div>
            <div class="method-item">
              <van-icon name="qq" size="24" color="#000" />
              <span>QQ</span>
            </div>
          </div>
        </div>

        <div class="agreement">
          登录即代表同意
          <span class="link">用户协议</span>
          和
          <span class="link">隐私政策</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { mobileRules, codeRules, passwordRules } from '@/utils/rules'
import { userApi } from '@/api/user'
import { useTokenStore } from '@/stores/index'

const tokenStore = useTokenStore()
const router = useRouter()
const loginType = ref('code') // 'code' 或 'password'
const showPassword = ref(false)

const formData = ref({
  phone: '',
  code: '',
  password: '',
})

// 倒计时相关
const countdown = ref(0)
// 判断是否正在倒计时
const isCountingDown = computed(() => countdown.value > 0)
const countDownText = computed(() => {
  return isCountingDown.value ? `${countdown.value}s` : '获取验证码'
})

// 判断登录按钮是否禁用
const submitDisabled = computed(() => {
  const { phone, code, password } = formData.value

  // 手机号必须填写
  if (!phone) return true

  // 根据登录方式判断
  if (loginType.value === 'code') {
    return !code
  } else {
    return !password
  }
})

// 发送验证码
const sendCode = async () => {
  if (!formData.value.phone) {
    showToast('请输入手机号')
    return
  }
  if (!/^1[3-9]\d{9}$/.test(formData.value.phone)) {
    showToast('请输入正确的手机号')
    return
  }

  try {
    await userApi.sendCode(formData.value.phone)
    // 开始倒计时
    countdown.value = 60
    const timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
    showToast('验证码已发送')
  } catch (error) {
    // 错误已在请求拦截器中处理
    console.log(error)
  }
}

// 提交表单
const onSubmit = async () => {
  try {
    let res
    if (loginType.value === 'code') {
      res = await userApi.loginByCode({
        phone: formData.value.phone,
        code: formData.value.code,
      })
    } else {
      res = await userApi.loginByPassword({
        phone: formData.value.phone,
        password: formData.value.password,
      })
    }
    showToast('登录成功')
    // 保存token
    tokenStore.setToken(res)
    router.replace('/home')
  } catch (error) {
    // 错误已在请求拦截器中处理
    console.log(error)
  }
}

// 忘记密码
const forgetPassword = () => {
  showToast('忘记密码')
  // TODO: 跳转到忘记密码页面
}

// 返回上一页
const goBack = () => {
  if (router.options.history.state.back) {
    router.back()
  } else {
    router.push('/')
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: #f7f8fa;
  color: #000;
}

.login-header {
  display: flex;
  align-items: center;
  padding: 16px;
}

.header-text {
  margin-left: 12px;
  font-size: 18px;
  font-weight: 600;
}

.login-content {
  padding: 20px;
}

.logo-wrap {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 40px 0;
}

.logo {
  width: 80px;
  height: 80px;
  border-radius: 20px;
}

.slogan {
  margin-top: 12px;
  font-size: 16px;
  font-weight: 600;
  color: #000;
}

.login-form {
  margin-top: 40px;
}

:deep(.van-cell-group--inset) {
  margin: 0;
  background-color: transparent;
}

:deep(.van-field) {
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  margin-bottom: 12px;
}

:deep(.van-field__control) {
  color: #000;
}

:deep(.van-field__control::placeholder) {
  color: rgba(0, 0, 0, 0.5);
}

.submit-btn {
  margin-top: 24px;
}

:deep(.van-button--primary) {
  background: linear-gradient(to right, #fe2c55, #ff3b30);
  border: none;
}

.other-login {
  margin-top: 48px;
}

.divider {
  display: flex;
  align-items: center;
  justify-content: center;
  color: rgba(0, 0, 0, 0.5);
}

.line {
  width: 50px;
  height: 1px;
  background-color: rgba(0, 0, 0, 0.2);
  margin: 0 12px;
}

.login-methods {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

.method-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0 24px;
}

.method-item span {
  margin-top: 8px;
  font-size: 12px;
  color: rgba(0, 0, 0, 0.8);
}

.agreement {
  margin-top: 40px;
  text-align: center;
  font-size: 12px;
  color: rgba(0, 0, 0, 0.5);
}

.link {
  color: #000;
}
.login-type-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

/* 添加新样式 */
.login-type {
  display: flex;
  justify-content: center;
}

.login-type span {
  position: relative;
  padding: 0 16px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
}

.forget-password {
  text-align: right;
  font-size: 14px;
  color: #666;
}

.forget-password span {
  cursor: pointer;
}

:deep(.van-field__right-icon) {
  cursor: pointer;
  color: rgba(0, 0, 0, 0.6);
}

/* 添加禁用状态样式 */
:deep(.van-button--disabled) {
  opacity: 0.5;
  background: linear-gradient(to right, #fe2c55, #ff3b30);
}
</style>
